package netty.http.xml.codec;

import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-10-28 14:16:00
 */
public abstract class AbstractHttpXmlEncoder<T> extends MessageToMessageEncoder<T> {

    protected ByteBuf encode(HttpXmlRequest request){
        String jsonStr = request.getBody();
        String xmlStr = XmlUtil.mapToXmlStr(JSONObject.parseObject(jsonStr));
        ByteBuf body = Unpooled.copiedBuffer(xmlStr, CharsetUtil.UTF_8);
        return body;
    }

    protected ByteBuf encode(HttpXmlResponse response) throws Exception {
        String jsonStr = response.getResult();
        String xmlStr = XmlUtil.mapToXmlStr(JSONObject.parseObject(jsonStr));
        ByteBuf body = Unpooled.copiedBuffer(xmlStr, CharsetUtil.UTF_8);
        return body;
    }

}
